<template>
  <div class="rbac-page">
    <div class="header">
      <h2>角色管理（RBAC）</h2>
      <p class="desc">通过邮箱查找用户并调整其角色</p>
    </div>

    <div class="card">
      <div class="card-title">按邮箱搜索用户</div>
      <div class="search-row">
        <el-input
          v-model="email"
          placeholder="请输入邮箱，例如: user@example.com"
          clearable
          @keyup.enter="onSearch"
          class="email-input"
        />
        <el-button type="primary" :loading="searching" :disabled="!email" @click="onSearch">
          搜索
        </el-button>
      </div>

      <div v-if="searching" class="loading-tip">正在查询用户信息...</div>

      <template v-else>
        <div v-if="user" class="result-card">
          <div class="result-grid">
            <div class="item"><span class="label">ID：</span>{{ user.id }}</div>
            <div class="item"><span class="label">用户名：</span>{{ user.username }}</div>
            <div class="item"><span class="label">邮箱：</span>{{ user.email }}</div>
            <div class="item"><span class="label">当前角色：</span>
              <el-tag type="info">{{ user.role }}</el-tag>
            </div>
          </div>

          <el-divider />

          <el-form label-width="88px" class="form">
            <el-form-item label="设置新角色">
              <el-select
                v-model="selectedRole"
                placeholder="请选择角色"
                class="role-select"
                :disabled="user?.role === 'SUPER_ADMIN'"
              >
                <el-option v-for="r in roleOptions" :key="r" :label="r" :value="r" />
              </el-select>
            </el-form-item>
            <el-form-item label="分配权限">
              <div class="perm-block">
                <PermissionSelector
                  v-model="selectedPerms"
                  :available-permissions="adminStore.permissions"
                />
                <div v-if="!selectedPerms.length" class="perm-hint">（未选择任何权限）</div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :disabled="!selectedRole || selectedRole === user.role" :loading="saving" @click="onSave">
                保存
              </el-button>
              <el-button :disabled="saving" @click="resetSelection">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-empty v-else-if="searched" description="未找到该邮箱对应的用户" :image-size="120" />
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { User } from '@/types/User'
import { useAdminStore } from '@/stores/admin/admin'
import PermissionSelector from '@/components/adm/PermissionSelector.vue'

const email = ref('')
const searching = ref(false)
const saving = ref(false)
const searched = ref(false)
const user = ref<User | null>(null)

const adminStore = useAdminStore()

// 角色下拉：不允许选择 SUPER_ADMIN
const roleOptions = computed(() => {
  const base = (adminStore.roles && adminStore.roles.length
    ? adminStore.roles
    : (['USER', 'COUNSELOR', 'ADMIN', 'SUPER_ADMIN'] as User['role'][]))
  return base.filter(r => r !== 'SUPER_ADMIN') as User['role'][]
})

const selectedRole = ref<User['role'] | ''>('')
const selectedPerms = ref<string[]>([])

onMounted(async () => {
  if (!adminStore.roles || adminStore.roles.length === 0) {
    await adminStore.fetchRoles()
  }
  if (!adminStore.permissions || adminStore.permissions.length === 0) {
    await adminStore.fetchPermissions()
  }
})

const emailRe = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/

async function onSearch() {
  searched.value = false
  user.value = null
  selectedRole.value = ''

  const mail = email.value.trim()
  if (!emailRe.test(mail)) {
    ElMessage.warning('请输入有效的邮箱地址')
    return
  }

  searching.value = true
  try {
    const raw = await adminStore.searchUsersByEmail(mail)
    let found: any = null
    if (Array.isArray(raw)) {
      found = raw[0] ?? null
    } else if (raw && typeof raw === 'object') {
      const maybeList = (raw as any).list
      if (Array.isArray(maybeList)) {
        found = maybeList[0] ?? null
      } else if ((raw as any).user) {
        found = (raw as any).user
      } else {
        found = raw
      }
    }
    user.value = (found || null) as User | null
    selectedRole.value = user.value?.role ?? ''
    // 尝试从返回对象中读取权限（后端若返回）
    const perms = (found && (found as any).permissions) as string[] | undefined
    selectedPerms.value = Array.isArray(perms) ? perms.slice() : []
  } catch (e: any) {
    const msg = e?.message || '查询失败'
    ElMessage.error(msg)
    user.value = null
  } finally {
    searched.value = true
    searching.value = false
  }
}

function resetSelection() {
  selectedRole.value = user.value?.role ?? ''
  const perms = (user.value as any)?.permissions as string[] | undefined
  selectedPerms.value = Array.isArray(perms) ? perms.slice() : []
}

async function onSave() {
  if (!user.value || !selectedRole.value || selectedRole.value === user.value.role) return
  saving.value = true
  try {
    // 角色变化
    if (selectedRole.value !== user.value.role) {
      const updated = await adminStore.updateUserRole({ id: user.value.id, role: selectedRole.value })
      if (updated) {
        user.value = { ...user.value, role: selectedRole.value } as User
      }
    }
    // 权限变化（与当前记录对比，若 user 中无，则直接提交所选）
    const currentPerms = ((user.value as any)?.permissions as string[] | undefined) ?? []
    const changed = JSON.stringify([...currentPerms].sort()) !== JSON.stringify([...selectedPerms.value].sort())
    if (changed) {
      await adminStore.updateUserPermissions({ id: user.value.id, permissions: selectedPerms.value })
      // 本地同步
      ;(user.value as any).permissions = selectedPerms.value.slice()
    }
    ElMessage.success('已保存权限与角色设置')
  } catch (e: any) {
    ElMessage.error(e?.message || '更新失败')
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.rbac-page { max-width: 960px; margin: 0 auto; padding: 24px 16px; }
.header { margin-bottom: 12px; }
.header h2 { margin: 0; font-weight: 700; }
.header .desc { color: #666; }
.card { margin-top: 12px; background: #fff; border-radius: 12px; padding: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.06); }
.card-title { font-weight: 600; margin-bottom: 12px; }
.search-row { display: flex; gap: 12px; align-items: center; }
.email-input { flex: 1; }
.loading-tip { margin-top: 12px; color: #666; }
.result-card { margin-top: 16px; }
.result-grid { display: grid; grid-template-columns: repeat(2, minmax(0,1fr)); gap: 8px 16px; }
.item .label { color: #666; }
.role-select { min-width: 220px; }
.perm-block { margin-top: 12px; }
@media (max-width: 640px) { .result-grid { grid-template-columns: 1fr; } }
</style>
